package com.example.service.shopping;


import cn.hutool.core.date.DateUtil;
import com.example.common.Result;
import com.example.common.enums.OrderStatusEnum;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.exception.CustomException;
import com.example.mapper.appointment.UserMapper;
import com.example.mapper.medical.DoctorMapper;
import com.example.mapper.shopping.CartMapper;
import com.example.mapper.shopping.MedicinesMapper;
import com.example.mapper.shopping.MedicinesStyleMapper;
import com.example.mapper.shopping.OrderMapper;
import com.example.model.entity.appointment.User;
import com.example.model.entity.medical.Doctor;
import com.example.model.entity.other.Account;
import com.example.model.entity.shopping.Cart;
import com.example.model.entity.shopping.Medicines;
import com.example.model.entity.shopping.MedicinesStyle;
import com.example.model.entity.shopping.Order;
import com.example.model.vo.OrderVO;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.awt.color.CMMException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 药物订单表业务处理
 **/
@Service
public class OrderService {

    @Resource
    private OrderMapper orderMapper;
    @Resource
    private MedicinesMapper medicinesMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private DoctorMapper doctorMapper;
    @Resource
    private MedicinesStyleMapper medicinesStyleMapper;
    @Resource
    private CartMapper cartMapper;


    /**
     * 删除
     */
    public void deleteById(Integer id) {
        orderMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            orderMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateById(Order order) throws ParseException {
        if (order.getStatus()!=null&&order.getStatus().equals(OrderStatusEnum.STATUS_TAKE.getName())){
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            order.setDeliverTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(format));
        }
        orderMapper.updateById(order);
    }


    public void updatePay(Order order) {
        payAccount(order);
        order.setStatus(OrderStatusEnum.STATUS_DELIVERY.getName());
        orderMapper.updateById(order);
    }

    /**
     * 根据ID查询
     */
    public Order selectById(Integer id) {
        return orderMapper.selectById(id);
    }


    /**
     * 查询所有
     */
    public List<OrderVO> selectAll(Order order) {
        Account currentUser = TokenUtils.getCurrentUser();
        if(RoleEnum.USER.name().equals(currentUser.getRole())){
            order.setUserId(currentUser.getId());
        }else if(RoleEnum.DOCTOR.name().equals(currentUser.getRole())){
            order.setDoctorId(currentUser.getId());
        }
        return orderMapper.selectAll(order);
    }

    /**
     * 分页查询
     */
    public PageInfo<OrderVO> selectPage(Order order, Integer pageNum, Integer pageSize) {
        Account currentUser = TokenUtils.getCurrentUser();
        if(RoleEnum.USER.name().equals(currentUser.getRole())){
            order.setUserId(currentUser.getId());
        }else if(RoleEnum.DOCTOR.name().equals(currentUser.getRole())){
            order.setDoctorId(currentUser.getId());
        }
        PageHelper.startPage(pageNum, pageSize);
        List<OrderVO> list = orderMapper.selectAll(order);
        return PageInfo.of(list);
    }


    /**
     * 新增
     */
    public void add(Order order) throws ParseException {
        Account currentUser = TokenUtils.getCurrentUser();
        if (order.getStatus().equals(OrderStatusEnum.STATUS_DELIVERY.getName())){
            if (RoleEnum.USER.name().equals(currentUser.getRole())) {
                User user = userMapper.selectById(currentUser.getId());
                double account = user.getAccount();
                if (account < order.getAllPrice()) {
                    throw new CustomException(ResultCodeEnum.PAY_EXIT_NO);
                }
                user.setAccount(account - order.getAllPrice());
                userMapper.updateById(user);
            } else if (RoleEnum.DOCTOR.name().equals(currentUser.getRole())) {
                order.setDoctorId(currentUser.getId());
                Doctor doctor = doctorMapper.selectById(currentUser.getId());
                double account = doctor.getAccount();
                if (account < order.getAllPrice()) {
                    throw new CustomException(ResultCodeEnum.PAY_EXIT_NO);
                }
                doctor.setAccount(account - order.getTotalPrice());
                doctorMapper.updateById(doctor);
            }
        }
        for (Cart cart : order.getCartData()) {
            Order dbOrder = new Order();
            BeanUtils.copyProperties(order, dbOrder);
            if (RoleEnum.USER.name().equals(currentUser.getRole())) {
                dbOrder.setUserId(currentUser.getId());
            }else if (RoleEnum.DOCTOR.name().equals(currentUser.getRole())) {
                dbOrder.setDoctorId(currentUser.getId());
            }
            // 获取当前日期时间，并格式化成 "yyyy-MM-dd" 格式
            dbOrder.setOrderId(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
            // 获取当前日期时间，并格式化成 "yyyy-MM-dd" 格式
            String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            // 设置订单时间
            dbOrder.setOrderData(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(format));
            // 获取当前日期时间，并加上3天，然后格式化成 "yyyy-MM-dd HH:mm:ss" 格式
            LocalDateTime deliveryDateTime = LocalDateTime.now().plusDays(3);
            String deliverTime = DateUtil.format(deliveryDateTime, "yyyy-MM-dd HH:mm:ss");
            // 设置发货时间
            dbOrder.setDeliverTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(deliverTime));
            dbOrder.setNum(cart.getNum());
            MedicinesStyle medicinesStyle = medicinesStyleMapper.selectById(cart.getMedicinesStyleId());
            Double price = medicinesStyle.getPrice();
            dbOrder.setTotalPrice(cart.getNum()*price);
            dbOrder.setMedicinesStyleId(cart.getMedicinesStyleId());
            dbOrder.setBusinessId(cart.getBusinessId());
            orderMapper.insert(dbOrder);
            //增加商品销量
            Medicines medicines = medicinesMapper.selectById(cart.getMedicinesId());
            medicines.setCount(medicines.getCount()+cart.getNum());
            medicinesMapper.updateById(medicines);
            // 把购物车里对应的商品删掉
            cartMapper.deleteById(cart.getId());
        }
    }
    /**
     * 下单
     */
    public void pay(Order order) throws ParseException {
        payAccount(order);
        order.setOrderId(DateUtil.format(new Date(), "yyyyMMddHHmmss"));
        // 获取当前日期时间，并格式化成 "yyyy-MM-dd" 格式
        String format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        // 设置订单时间
        order.setOrderData(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(format));
        // 获取当前日期时间，并加上3天，然后格式化成 "yyyy-MM-dd HH:mm:ss" 格式
        LocalDateTime deliveryDateTime = LocalDateTime.now().plusDays(3);
        String deliverTime = DateUtil.format(deliveryDateTime, "yyyy-MM-dd HH:mm:ss");
        // 设置发货时间
        order.setDeliverTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(deliverTime));
        orderMapper.insert(order);
        //增加商品销量
        Medicines medicines = medicinesMapper.selectById(order.getMedicinesId());
        medicines.setCount(medicines.getCount()+order.getNum());
        medicinesMapper.updateById(medicines);
    }

    public void payAccount(Order order) {
        Account currentUser = TokenUtils.getCurrentUser();
        if (RoleEnum.USER.name().equals(currentUser.getRole())) {
            order.setUserId(currentUser.getId());
            User user = userMapper.selectById(currentUser.getId());
            double account = user.getAccount();
            if (account < order.getTotalPrice()) {
                throw new CustomException(ResultCodeEnum.PAY_EXIT_NO);
            }
            user.setAccount(account - order.getTotalPrice());
            userMapper.updateById(user);
        } else if (RoleEnum.DOCTOR.name().equals(currentUser.getRole())) {
            order.setDoctorId(currentUser.getId());
            Doctor doctor = doctorMapper.selectById(currentUser.getId());
            double account = doctor.getAccount();
            if (account < order.getTotalPrice()) {
                throw new CustomException(ResultCodeEnum.PAY_EXIT_NO);
            }
            doctor.setAccount(account - order.getTotalPrice());
            doctorMapper.updateById(doctor);
        }
    }

    public Order selectByOrderNo(String orderId) {
        return orderMapper.selectByOrderNo(orderId);
    }
}
